package com.fengmi.security;

import cn.hutool.json.JSONUtil;
import com.fengmi.entity.SysUser;
import com.fengmi.utils.security.JwtUtils;
import com.fengmi.utils.security.RsaUtils;
import com.fengmi.vo.ResultVO;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;

/**
 * 作者：陈学虎
 * 时间：2021/7/14 0014 下午 7:17
 */
public class MyBasicAuthenticationFilter extends BasicAuthenticationFilter {
    public MyBasicAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        try {
            //如果是登录请求，直接放行
            String requestURI = request.getRequestURI();
            if ("/user/login".equals(requestURI)){
//                放行
                 chain.doFilter(request,response);
                 return;
            }

            if ("/user/verify".equals(requestURI)){
//                放行
                chain.doFilter(request,response);
                return;
            }

            //从请求头中获取token
            String token = request.getHeader("token");
            if (StringUtils.isEmpty(token)){
    //            响应（json）
                ResultVO resultVO = new ResultVO(false,"token不能为空");
                response(response,resultVO);
            }
            //校验并解析token
            String path = ResourceUtils.getFile("classpath:rsa.pub").getPath();
            PublicKey publicKey = RsaUtils.getPublicKey(path);
            SysUser sysUserJwt = (SysUser) JwtUtils.getInfoFromToken(token, publicKey, SysUser.class);

            List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList
                    (sysUserJwt.getRole() + "," + sysUserJwt.getPermission());
            //将用户信息放入springsecurity中
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken
                    (sysUserJwt,null,grantedAuthorities);
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);


            //放行
            chain.doFilter(request,response);
        } catch (Exception e) {
            e.printStackTrace();
            ResultVO resultVO = new ResultVO(false,"token令牌无效");
            response(response,resultVO);
        }
    }

    private void  response(HttpServletResponse response, ResultVO res){
        try {
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            PrintWriter out = response.getWriter();

            out.write(JSONUtil.toJsonPrettyStr(res));
            out.flush();
            out.close();
        }catch (Exception e){

        }

    }
}
